package com.han.walkman.timer;

import com.han.walkman.entity.VisitedBusinessEntity;
import com.han.walkman.service.VisitedBusinessService;
import com.han.walkman.util.ExcelUtils;
import com.han.walkman.util.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.sql.Date;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: Hanjiafeng
 * @Date: 2020/7/8
 * @Desc:
 */
@Slf4j
@Component
@EnableScheduling
public class VisitedBusinessTimer {
    private final VisitedBusinessService visitedBusinessService;
    private final MailService mailService;

    @Value("${root.storage.path}")
    private String storagePath;

    @Value("${mail.to}")
    private String to;

    public VisitedBusinessTimer(VisitedBusinessService visitedBusinessService, MailService mailService) {
        this.visitedBusinessService = visitedBusinessService;
        this.mailService = mailService;
    }

    /**
     * 每晚七点发送邮件
     */
    @Scheduled(cron = "00 00 19 * * ?")
    public void sayHello() {
        Date date = new Date(System.currentTimeMillis());
        log.info("开始统计" + date + "走访计划");

        //构建搜索条件
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                //包含字符串
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);
        VisitedBusinessEntity entity = new VisitedBusinessEntity();
        entity.setVisitDate(date);
        Example<VisitedBusinessEntity> entityExample = Example.of(entity, exampleMatcher);

        List<VisitedBusinessEntity> visitedBusinessEntityList = visitedBusinessService.findAll(entityExample);
        //如果没有查询到今日上报商机，则返回不发送
        if (visitedBusinessEntityList.isEmpty()) {
            log.info("今日无商机，不发送邮件");
            return;
        }
        Map<String, List<Map<String, String>>> sheetMap = new LinkedHashMap<>();
        List<Map<String, String>> mapList = new ArrayList<>();
        for (VisitedBusinessEntity entity1 : visitedBusinessEntityList) {
            mapList.add(entity1.generateMap());
        }
        sheetMap.put("sheet1", mapList);
        String subject = date + "";
        String fileName = subject + ".xls";
        String path = storagePath + "/" + fileName;
        ExcelUtils.writeToLocal(path, sheetMap);

        log.info("开始发送统计邮件");
        mailService.sendAttachmentsMail(to, subject, "商机走访", path);
    }
}
